package com.pet.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pet.service.CheckInfoService;
import com.pet.service.SysUserService;
import com.pet.system.SysUser;
import com.pet.utils.JwtHelper;
import com.pet.utils.Result;
import com.pet.utils.Sample;
import com.pet.vo.LoginVo;
import com.pet.system.SysCheckInfo;
import com.pet.vo.RegisterVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.util.*;

@CrossOrigin("*")
@RestController
@Api(tags = "登录管理控制器")
@RequestMapping(value = "/lovePet/system/index")
public class LoginController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    Sample sample;
    @Autowired
    CheckInfoService checkInfoService;

    /**
     * 登录接口
     *
     * @return
     */
    @ApiOperation("登录方法")
    @PostMapping("/login")
    public Result login(@ApiParam("登录信息") @RequestBody LoginVo loginVo) {
        return Result.ok("1");
    }

    @ApiOperation("info方法")
    @GetMapping("/info")
    public Result info(@ApiParam("前端请求头") HttpServletRequest request) {
        //a.获取请求头的 token 字符串
        String token = request.getHeader("token");

        //b.从token 字符串获取用户名称 (id)
        String username = JwtHelper.getUsername(token);

        // c.根据用户名称获取用户信息 （a.基本信息  b.菜单权限信息  和 c.按钮权限信息）
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", username));

        return Result.ok(sysUser);
    }

    @ApiOperation("infoVueAdmin，后台管理服后端info方法")
    @GetMapping("/infoVueAdmin")
    public Result infoVueAdmin(@ApiParam("后台管理请求头") HttpServletRequest request) {
        //a.获取请求头的 token 字符串
        String token = request.getHeader("token");

        //b.从token 字符串获取用户名称 (id)
        String username = JwtHelper.getUsername(token);

        // c.根据用户名称获取用户信息 （a.基本信息  b.菜单权限信息  和 c.按钮权限信息）
        Map<String, Object> map = sysUserService.getUserInfo(username);

        return Result.ok(map);
    }


    /*
    短信发送
    测试阶段，测试号码需要绑定阿里云
     */
    @ApiOperation("短信发送接口")
    @GetMapping("/checkCode")
    public Result SendMessage(@ApiParam("短信信息") String phoneNum) throws Exception {
        //清除该号码下的先前发的所有验证码，保持验证码唯一
        checkInfoService.remove(new QueryWrapper<SysCheckInfo>().eq("phoneNumber", phoneNum));

//        if (sysUserService.getOne(new QueryWrapper<SysUser>().eq("phone",phoneNum))!=null){
//            return Result.fail("该电话号码已注册");
//        }
        //四位随机数
        String checkCode = "";
        int[] i = new Random().ints(4, 0, 9).toArray();
        for (int num : i) {
            checkCode += Integer.toString(num);
        }
        sample.sendMessage(phoneNum, checkCode);
        SysCheckInfo sysCheckInfo = new SysCheckInfo();
        sysCheckInfo.setCheckCode(checkCode);
        sysCheckInfo.setPhoneNumber(phoneNum);
        boolean b = checkInfoService.save(sysCheckInfo);
        return b ? Result.ok() : Result.fail();
    }

    @ApiOperation("注册")
    @PostMapping("/register")
    public Result register(@ApiParam("注册信息") @RequestBody RegisterVo registerVo) {//注册对象封装了前端表单字段

        QueryWrapper queryWrapper = new QueryWrapper();

        queryWrapper.eq("phoneNumber", registerVo.getPhoneNumber());

        queryWrapper.eq("checkCode", registerVo.getCheckCode());

        SysCheckInfo sysCheckInfo = checkInfoService.getOne(queryWrapper);
        SysUser sysUser = new SysUser(registerVo);
//        传入用户参数
        boolean isUseful = System.currentTimeMillis() - sysCheckInfo.getCreateTime().getTime() < 600 * 1000;
        boolean equals = sysCheckInfo.getCheckCode().equals(registerVo.getCheckCode());
        if (isUseful && equals) {
            String encode = new BCryptPasswordEncoder().encode(sysUser.getPassword());
            sysUser.setPassword(encode);
            //插入用户
            boolean b = sysUserService.save(sysUser);
            //删除验证码
            checkInfoService.remove(queryWrapper);
            return b ? Result.ok() : Result.fail();
        }
        if (!isUseful) {
            return Result.fail("验证码过期");
        }
        return Result.fail("验证码错误");
    }

    /**
     * 退出
     *
     * @return
     */
    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public Result logout() {
        return Result.ok();
    }
}
